using System;
using System.IO;
using System.Globalization;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Xml;

namespace Website
{
    public sealed class SeeOtherActionResult : ActionResult
    {
        private const string HtmlTemplate = "<html>" +
            "<head><title>The information you requested has been found</title></head>" +
            "<body>" +
            "<h1>The information you requested has been found</h1>" +
            "<p><a id=\"location\" href=\"\"></a></p>" +
            "</body>" +
            "</html>";

        public SeeOtherActionResult(string location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }

            if (0 == location.Length)
            {
                throw new ArgumentOutOfRangeException("location");
            }

            this.Location = location;
        }

        public string Location
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            Uri location = new Uri(context.HttpContext.Request.Url, new Uri(this.Location, UriKind.Relative));

            response.StatusCode = (int)HttpStatusCode.SeeOther;
            response.AppendHeader("Location", location.AbsoluteUri);
            response.ContentType = "text/html";
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetExpires(DateTime.UtcNow.AddDays(1));
            response.Cache.VaryByHeaders["Accept"] = true;
            response.Cache.VaryByHeaders["Accept-Language"] = true;

            XmlDocument content = new XmlDocument();
            content.LoadXml(HtmlTemplate);
            content.SelectSingleNode("/html/body/p/a[@id='location']/@href").Value = location.AbsoluteUri;
            content.SelectSingleNode("/html/body/p/a[@id='location']").InnerText = HttpUtility.HtmlEncode(location.AbsoluteUri);

            response.Write(content.OuterXml);
        }
    }
}